package com.sctvcloud.renhe.ui.utils.update;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.dialog.AlertDialogFragment;
import com.ruihang.generalibrary.utils.UrlUtils;
import com.sctvcloud.renhe.BuildConfig;
import com.sctvcloud.renhe.R;
import com.sctvcloud.renhe.application.Constances;
import com.sctvcloud.renhe.beans.FVersionInfo;
import com.sctvcloud.renhe.ui.dialog.DownLoadDialogFragment;
import com.sctvcloud.renhe.ui.dialog.UpdateDialogFragment;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @author coolszy
 * @date 2012-4-26
 * @blog http://blog.92coding.com
 */

public class DownloadManager {

    public static final String TAG_DOWNLOAD = "tag_download";
    public static final String TAG_NOTICE = "tag_notice";

    /* 下载中 */
    private static final int DOWNLOAD = 1;
    /* 下载结束 */
    private static final int DOWNLOAD_FINISH = 2;
    /* 下载失败 */
    private static final int DOWNLOAD_FAIL = 3;


    /**
     * 询问权限时的request code
     */
    public static final int PERMISSION_REQUEST = 8001;
    /* 保存解析的XML信息 */
    // HashMap<String, String> mHashMap;
    // private WoVersionInfo version;
    private String fileUrl;

    private String fileName;
    /* 下载保存路径 */
    private String mSavePath;
    /* 记录进度条数量 */
    private int progress;
    private int allSize = 0;
    private int curSize = 0;
    /* 是否取消更新 */
    private boolean cancelUpdate = false;

    private Context mContext;
    /* 更新进度条 */
    private ProgressBar mProgress;
    private TextView tvProgress, tv_cancel;
    private DownLoadDialogFragment mDownloadDialog;
    private UpdateDialogFragment noticeDialog;
    public static boolean isUpdating = false;
    private OnDialogAction action;
    private FVersionInfo version;
    private OnDownloadSuccess downloadListener;
    private downloadApkThread downloadThread;
    private boolean permissionResult = true;
    private DownloadListener listener;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                // 正在下载
                case DOWNLOAD:
                    mDownloadDialog.setProgress(progress, curSize + "/" + allSize + " (" + progress + "%)");
                    break;
                case DOWNLOAD_FINISH:
                    // 安装文件
                    if (mDownloadDialog != null && mDownloadDialog.isShowing()) {
                        mDownloadDialog.dismiss();
                    }
                    if(null!=downloadListener){
                        downloadListener.onDownloadSuccess(mSavePath, fileName);
                    }
                    break;
                case DOWNLOAD_FAIL:
                    mDownloadDialog.dismissAllowingStateLoss();
                    Toast.makeText(mContext, "下载失败", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }

        ;
    };

    public interface OnDialogAction {
        void onPositiveButtonClick();

        void OnNegativeButtonClick();

        void onUploadFailed();
    }

    public interface DownloadListener {
        void onDownloadFinish(String fileUrl, String fileName, String path);
    }

    public void setAction(OnDialogAction action) {
        this.action = action;
    }


    public DownloadManager(Context context, String fileName, String fileUrl) {
        this.mContext = context;
        this.fileName = fileName;
        this.fileUrl = fileUrl;
    }

    public DownloadManager(Context context, FVersionInfo version) {
        this.mContext = context;
        this.version = version;
        this.fileName = version.getVersionName() + ".apk";
//        String tempUrl = "http://172.16.17.36:8080";
        this.fileUrl = UrlUtils.linkUrls(Constances.ST_BASE_URL, version.getAddress());
    }

    public void downloadFile(DownloadListener listener) {
        this.listener = listener;
        // 启动新线程下载软件
        if (TextUtils.isEmpty(fileUrl)) {
            return;
        }
        if (TextUtils.isEmpty(fileName)) {
            String suffixes = "gif";
            Pattern pat = Pattern.compile("[\\w]+[\\.](" + suffixes + ")");//正则判断
            Matcher mc = pat.matcher(fileUrl.toLowerCase());//条件匹配
            while (mc.find()) {
                fileName = mc.group();//截取文件名后缀名
            }
            if (TextUtils.isEmpty(fileName)) {
                return;
            }
        }
        new downloadApkThread().start();
    }

    /**
     * 检测软件更新
     */
    public boolean checkUpdate(int oldVersion, int newVersion, boolean isForce, String content, FragmentManager fm) {
        if (isUpdate(oldVersion, newVersion)) {
            // 显示提示对话框
            return showNoticeDialog(isForce, content, fm);
        } else {
            return false;
        }
    }

    /**
     * 检查软件是否有更新版本
     *
     * @return
     */
    private boolean isUpdate(int oldVersion, int newVersion) {
        return newVersion > oldVersion;
    }

    private boolean isForce = false;//是否强制更新
    private String updateContent;

    public boolean showNoticeDialog(FragmentManager fm) {
        if (noticeDialog == null) {
            noticeDialog = new UpdateDialogFragment().setForce(isForce);
            noticeDialog.setCancelOut(false);
            noticeDialog.setMsgStr(updateContent);
            noticeDialog.setOnViewClick(new AlertDialogFragment.OnViewClick() {
                @Override
                public boolean onViewClick(View view, int viewItem, int mode) {
                    if (viewItem == AlertDialogFragment.VIEW_ITEM_OK) {
                        action.onPositiveButtonClick();
                        JLog.e("tatt  in click ok");
                        return true;
                    } else if (viewItem == AlertDialogFragment.VIEW_ITEM_CANCLE) {
                        if (noticeDialog.isForce()) {
                            noticeDialog.dismissAllowingStateLoss();
                            System.exit(0);
                        } else {
                            noticeDialog.dismissAllowingStateLoss();
                            action.OnNegativeButtonClick();
                        }
                    }
                    return false;
                }
            });
        } else if (noticeDialog.isResumed()) {
            return true;
        }
        noticeDialog.show(fm, TAG_NOTICE);
        return true;
    }

    /**
     * 显示软件更新对话框
     */
    private boolean showNoticeDialog(boolean isForce, String content, FragmentManager fm) {
        // 构造对话框
        this.isForce = isForce;
        this.updateContent = content;
        curSize = 0;
        allSize = 0;
        progress = 0;
        return showNoticeDialog(fm);
    }

    public void onUpdateAction(FragmentManager fm) {
        cancelUpdate = false;
        // 显示下载对话框
        showDownloadDialog(fm);
    }

    private boolean isDownloadDissed() {
        return mDownloadDialog == null || !mDownloadDialog.isResumed() || mDownloadDialog.isHidden();
    }

    private boolean isNoticeDissed() {
        return noticeDialog == null || !noticeDialog.isResumed() || noticeDialog.isHidden();
    }

    public boolean hasCheckUpdateFinish() {
        return isDownloadDissed() && isNoticeDissed();
    }

    /**
     * 显示软件下载对话框
     */
    private void showDownloadDialog(FragmentManager fm) {
        // 构造软件下载对话框
        if (mDownloadDialog == null) {
            mDownloadDialog = new DownLoadDialogFragment();
            mDownloadDialog.setCancelClick(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mDownloadDialog.dismissAllowingStateLoss();
                    // 设置取消状态
                    cancelUpdate = true;
                    showNoticeDialog(isForce, updateContent, mDownloadDialog.getActivity().getSupportFragmentManager());
                }
            });
        } else if (mDownloadDialog.isResumed()) {
            return;
        }

        mDownloadDialog.show(fm, TAG_DOWNLOAD);
        JLog.e("has call down dialog show");
        // 现在文件
        downloadApk();
    }

    /**
     * 下载apk文件
     */
    private void downloadApk() {
        // 启动新线程下载软件
        new downloadApkThread().start();
    }

    public void notifyPermission(boolean isSuc) {
        permissionResult = isSuc;
        if (downloadThread != null && downloadThread.isAlive() && !downloadThread.isInterrupted()) {
            downloadThread.notify();
        }
    }

    /**
     * 下载文件线程
     *
     * @author coolszy
     * @date 2012-4-26
     * @blog http://blog.92coding.com
     */
    private class downloadApkThread extends Thread {
        @Override
        public void run() {
            try {
                // 判断SD卡是否存在，并且是否具有读写权限
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    if (permissionResult) {
                        download(getId());
                        this.interrupt();
                    } else {
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(mContext, R.string.updateFail_permission, Toast.LENGTH_SHORT).show();
                                if (action != null) {
                                    action.onUploadFailed();
                                }
                            }
                        });
                    }
                } else {
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(mContext, "无SD卡，更新失败！", Toast.LENGTH_SHORT).show();
                            if (action != null) {
                                action.onUploadFailed();
                            }
                        }
                    });
                    boolean isDowned = false;
//
                }
            } catch (MalformedURLException e) {
                if (mHandler != null) {
                    mHandler.sendEmptyMessage(DOWNLOAD_FAIL);
                }
                e.printStackTrace();
            } catch (IOException e) {
                if (mHandler != null) {
                    mHandler.sendEmptyMessage(DOWNLOAD_FAIL);
                }
                e.printStackTrace();
            }
            // 取消下载对话框显示
            //  mDownloadDialog.dismiss();
        }
    }

    private void download(long threadId) throws MalformedURLException, IOException {
        // 获得存储卡的路径
        String sdpath = Environment.getExternalStorageDirectory() + "/";
        mSavePath = sdpath + "download/";
        JLog.d("fileUrl:" + fileUrl);
        URL url = new URL(fileUrl);
        // 创建连接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.connect();
        // 获取文件大小
        int length = conn.getContentLength();
        allSize = length;
        // 创建输入流
        InputStream is = conn.getInputStream();

        File file = new File(mSavePath);
        // 判断文件目录是否存在
        if (!file.exists()) {
            file.mkdir();
        }
        File apkFile = new File(mSavePath, fileName);
        FileOutputStream fos = new FileOutputStream(apkFile);
        int count = 0;
        // 缓存
        byte buf[] = new byte[1024];
        // 写入到文件中
        do {
            int numread = is.read(buf);
            count += numread;
            curSize = count;
            // 计算进度条位置
            progress = (int) (((float) count / length) * 100);
            JLog.d("progress:" + progress);
            // 更新进度
            mHandler.sendEmptyMessage(DOWNLOAD);
            if (numread <= 0) {
                // 下载完成
                mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
                if (listener != null) {
                    listener.onDownloadFinish(fileUrl, fileName, mSavePath);
                }
                break;
            }
            // 写入文件
            fos.write(buf, 0, numread);
        } while (count > 0 && !cancelUpdate);// 点击取消就停止下载.
        fos.close();
        is.close();
    }

    /**
     * 安装APK文件
     */
    private void installApk() {
        File apkfile = new File(mSavePath, fileName);
        if (!apkfile.exists()) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri u = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            u = FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID+".provider", apkfile);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            u = Uri.fromFile(apkfile);
        }
        intent.setDataAndType(u, "application/vnd.android.package-archive");
        mContext.startActivity(intent);
    }

    public void setDownloadListener(OnDownloadSuccess downloadListener) {
        this.downloadListener = downloadListener;
    }

    public interface OnDownloadSuccess {
        void onDownloadSuccess(String mSavePath, String fileName);
    }
}
